<template>
  <!-- 接单大厅 -->
  <view class="hall" :style="hallStyle">
    <left-side
      :show="show"
      @close="show = false"
      @onTrigger="(e) => (currentIndex = e)"
    />
    <view
      class="hall-nav-placeholder"
      :style="{
        height: navHeight,
        background: `url(${getImgSrc('/home/home_bg@2x.png')}) no-repeat`,
      }"
    />
    <view class="hall-layout">
      <view class="hall-nav">
        <image
          mode="widthFix"
          :src="getImgSrc('/home/home_bg@2x.png')"
          class="hall-nav-bg"
        />
        <view class="hall-nav-operator">
          <view class="hall-nav-operator-left">
            <image
              mode="scaleToFill"
              :src="vuex_user.head || getImgSrc('/home/icon_home_my@2x.png')"
              class="avatar hall-nav-icon"
              @tap="show = true"
            />
          </view>
          <view class="hall-nav-operator-center">
            <u-dropdown
              ref="uDropdown"
              inactive-color="#fff"
              active-color="#fff"
            >
              <u-dropdown-item :title="statusText">
                <view class="slot-content" style="background-color: #ffffff">
                  <view
                    v-for="item in statusList"
                    :key="item.value"
                    @tap="triggerToChangeStatus(item.value)"
                    :class="
                      'drop-item u-text-center u-content-color u-p-t-20 u-p-b-20' +
                      (item.value === currentStatus ? ' active' : '')
                    "
                    >{{ item.name }}
                    <u-icon
                      size="32"
                      class="drop-item-icon"
                      name="checkbox-mark"
                    />
                  </view>
                </view>
              </u-dropdown-item>
              <u-dropdown-item :title="schoolText">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 400rpx">
										<view class="search" style="background: #ffffff">
										  <u-search
										    v-model="keywords1"
										    @custom="search1"
										    @search="search1"
										  ></u-search>
										</view>
                    <view
                      v-for="item in siteList"
                      :key="item.value"
                      @tap="triggerToChangeSite(item)"
                      :class="
                        'drop-item u-text-center u-content-color u-p-t-20 u-p-b-20' +
                        (item.value === currentSite ? ' active' : '')
                      "
                      ><text>{{ item.name }}</text>
                      <u-icon
                        size="32"
                        class="drop-item-icon"
                        name="checkbox-mark"
                      />
                    </view>
                  </scroll-view>
                </view>
              </u-dropdown-item>
            </u-dropdown>
          </view>
          <view class="hall-nav-operator-right">
            <image
              mode="scaleToFill"
              :src="getImgSrc('/home/icon_home_news@2x.png')"
              class="news hall-nav-icon"
              @tap="toMessage"
            />
            <image
              mode="scaleToFill"
              :src="getImgSrc('/home/icon_home_refresh@2x.png')"
              class="refresh hall-nav-icon"
              @tap="upCallback"
            />
          </view>
        </view>
      </view>
      <view class="hall-dashboard">
        <view class="dashboard">
          <view class="dashboard-item">
            <view class="amount">{{ fee.toFixed(2) }}</view>
            <view class="desc">收入（元）</view>
          </view>
          <view class="dashboard-item">
            <view class="amount">{{ orderCount }}</view>
            <view class="desc">完成订单（个）</view>
          </view>
        </view>
      </view>

      <view
        class="hall-tabs"
        v-if="
          this.currentIndex !== '' &&
          Array.isArray(taskStatusList) &&
          taskStatusList.length
        "
      >
        <u-tabs-swiper
          :list="taskStatusList"
          font-size="30"
          bar-height="12"
          bar-width="86"
          :bar-style="{
            'border-radius': '0',
            bottom: '10px',
            background: 'linear-gradient(90deg, #FFE6A3, #FFCB40)',
          }"
          active-color="#4E95FC"
          :gutter="66"
          :is-scroll="true"
          :current="currentIndex"
          @change="refreshBySwitch"
        >
        </u-tabs-swiper>
        <view
          class="task-list-item"
          v-for="(item, idx) in taskStatusList"
          :key="item.value"
        >
          <view v-if="currentIndex === idx">
            <task
              v-for="data in dataList[currentIndex]"
              :key="data.tradeNo + idx"
              :data="data"
              @onRefresh="upCallback"
              :currentSite="currentSite"
              :process="item.value"
              :currentStatus="currentStatus"
            />
          </view>
        </view>
      </view>
    </view>
    <!-- </mescroll-body-diy> -->
  </view>
</template>
<script>
import { checkLogin } from "@/common/util.js";
import { getLocation } from "@/common/location.js";
import Task from "./task.vue";
import MescrollBodyDiy from "@/uni_modules/mescroll-uni/components/mescroll-diy/beibei/mescroll-body.vue";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import leftSide from "./runnerLeftSide.vue";

export default {
  name: "hall",
  mixins: [MescrollMixin], // 使用mixin
  components: {
    task: Task,
    leftSide,
    MescrollBodyDiy,
  },
  data() {
    return {
      startLoadId: null,
      fee: 0,
      orderCount: 0,
      show: false,
      statusList: [],
      counts: [],
      siteList: [],
			siteListData: [],
			keywords1:'',
      taskStatusList: [],
      currentIndex: "",
      currentSite:
        (uni.getStorageSync("currentSite") || "").replace(/\"/g, "") || "",
      currentStatus: uni.getStorageSync("currentStatus") || "",
      refreshFlag: false,
      isInit: false,
      dataList: {
        default: [],
      },
      upOption: {
        page: {
          size: 10, // 每页数据的数量,默认10
        },
        noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
        empty: {
          tip: "暂无相关数据",
        },
      },
    };
  },
  onLoad(option) {
    this.$u.vuex("vuex_flag", "runner");
  },
  onShow() {
    checkLogin(() => {
      uni.redirectTo({
        url: "/pages/sys/home/index",
      });
    });
    this.startLoadId = setInterval(this.sync, 5000);
    this.upCallback();
  },
  onHide() {
    if (this.startLoadId) {
      clearTimeout(this.startLoadId);
      this.startLoadId = null;
    }
  },
  created() {
    this.queryHeadDataSource();
  },
  computed: {
    hallStyle() {
      return {
        "padding-top": this.vuex_safeArea.top + "px",
      };
    },
    statusText() {
      const status = this.statusList.find(
        (d) => d.value === this.currentStatus
      );
      return status ? status.name.slice(0, 2) : "unkown";
    },
    schoolText() {
      const site = this.siteList.find((d) => d.value === this.currentSite);
      return site ? site.name.slice(0, 2) : "未选择";
    },
    info() {
      return JSON.stringify(uni.getSystemInfoSync(), null, 2);
    },
    navHeight() {
      return getApp().globalData.navHeight + "px";
    },
  },
  watch: {
    refreshFlag(newValue, oldValue) {
      if (newValue && !oldValue) {
        this.refresherreOrder();
      }
    },
    currentSite(newValue, oldValue) {
      uni.setStorageSync("currentSite", JSON.stringify(newValue));
      this.upCallback();
    },
    currentStatus: {
      handler(newValue) {
        uni.setStorageSync("currentStatus", newValue);
        this.triggerToResponseStatusChanged();
      },
      immediate: true,
    },
    currentIndex(newValue) {
      this.upCallback();
    },
  },
  methods: {
		search1(e) {
		  let data = [];
		  let list = [];
			console.log(e)
		  if (this.siteListData && this.siteListData != "") {
		    data = JSON.parse(this.siteListData);
		    if (e) {
		      data.map((item) => {
						console.log(item)
		        if (item.name.indexOf(e) != -1) {
		          list.push(item);
		        }
		      });
		    } else {
		      list = data;
		    }
		    this.siteList = list;
		  }
		},
    async sync() {
      const res = await getLocation();
      this.$u.api.invokeSyncLocation({
        lat: res.latitude,
        lon: res.longitude,
      });
    },
    async triggerToResponseStatusChanged() {
      this.$u.api.invokeModifyStatus({ state: this.currentStatus });
    },
    triggerToChangeSite(item) {
      this.currentSite = item.value;
      this.closeDropdown();
    },
    async queryHeadDataSource() {
      const data = await this.$u.api.queryHallHeadDataSource();
      if (data.code !== 200) {
        uni.showToast({
          title: "拉取初始化数据失败，请稍后重试",
          duration: 2000,
          icon: "none",
        });
        return;
      }
      this.statusList = (data.data.workState || []).map((d) => ({
        name: d.value,
        value: d.key,
      }));
      this.siteList = (data.data.site || []).map((d) => ({
        name: d.value,
        value: d.key,
      }));
			this.siteListData = JSON.stringify(this.siteList)
      this.taskStatusList = (data.data.type || []).map((d, idx) => ({
        name: d.value,
        value: d.key,
      }));
      this.fee = data.data.statistics.fee || 0;
      this.orderCount = data.data.statistics.orderCount || 0;
      this.taskStatusList.forEach((d, idx) => {
        this.dataList[idx] = [];
      });
      if (this.currentSite === "" && this.siteList.length) {
        this.currentSite = this.siteList.slice(0, 1).map((d) => d.value)[0];
      }
      if (this.currentStatus === "" && this.statusList.length) {
        this.currentStatus = this.statusList.slice(0, 1).map((d) => d.value)[0];
      }

      if (this.taskStatusList.length) {
        this.currentIndex = 0;
      }
    },
    upCallback() {
      const that = this;
      let api;
      uni.showLoading();
      const index = this.currentIndex;
      const key = index === "" ? "default" : index;
      // tab 对应的key
      const type =
        this.currentIndex === ""
          ? ""
          : this.taskStatusList[Number(this.currentIndex)].value;
      if (
        this.currentSite !== "" &&
        index !== "" &&
        Array.isArray(this.siteList) &&
        this.siteList.length
      ) {
        api = this.$u.api.queryHallTaskListBySite({
          siteId: Number(this.currentSite),
          type,
        });
      } else {
        api = this.$u.api.queryHallTaskList();
      }

      api
        .then((res) => {
          const list =
            res.data[
              [, "newPage", "waitPage", "ingPage", "endPage"][type || 1]
            ];

          that.taskStatusList = this.taskStatusList.map((d, idx) => ({
            ...d,
            count: res.data.counts[idx] || undefined,
          }));
          this.fee = res.data.statistics.fee || 0;
          this.orderCount = res.data.statistics.orderCount || 0;
          that.dataList[key] = list;
          this.$forceUpdate();
        })
        .catch(() => {
          //联网失败, 结束加载
        })
        .then(() => {
          uni.hideLoading();
        });
    },
    triggerToChangeStatus(status) {
      this.closeDropdown();
      this.currentStatus = status;
    },
    closeDropdown() {
      this.$refs.uDropdown.close();
    },
    refreshBySwitch(index) {
      this.currentIndex = index;
    },
    toMessage() {
      uni.navigateTo({
        url: "/pages/sys/user/runner-message",
      });
    },
  },
};
</script>
<style lang="scss">
.hall {
  /deep/.mescroll-downwarp .downwarp-content {
    // bottom: initial;
    // top: 0;
  }
	.search {
		padding: 20rpx;
	}
  &-scroll {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }

  &-nav-placeholder {
    width: 100%;
    position: relative;
    top: 0;
    left: 0;
    right: 0;
  }

  &-layout {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
  }

  &-nav {
    width: 100%;
    height: 208rpx;
    box-sizing: content-box;
    position: relative;

    &-bg {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      pointer-events: none;
    }

    .hall-nav-icon {
      position: absolute;
      top: 0;
      z-index: 99;
    }

    .avatar {
      left: 29rpx;
      width: 70rpx;
      height: 70rpx;
      border-radius: 50%;
      border: 2px solid #ffffff;
      background-color: #fff;
    }

    .news {
      width: 36rpx;
      height: 36rpx;
      right: 87rpx;
      top: 18rpx;
    }

    .refresh {
      width: 36rpx;
      height: 36rpx;
      right: 23rpx;
      top: 19rpx;
    }

    .drop-item {
      position: relative;

      &-icon {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        display: none;
      }

      &.active {
        color: #4e95fc;

        .drop-item-icon {
          display: inline-block;
        }
      }
    }

    /deep/.u-dropdown {
      position: absolute;
      left: 0;
      top: 0;

      .u-dropdown__menu {
        & > .u-dropdown__menu__item:first-child {
          flex-basis: 30%;
          flex-grow: 0;

          .u-flex {
            margin-left: 116rpx;
          }
        }

        & > .u-dropdown__menu__item:last-child {
          flex-basis: 40%;
          // flex-basis: calc(750rpx - 416rpx);
          flex-grow: 0;

          // .u-flex {
          // 	margin-left: 109rpx;
          // }
        }
      }
    }

    /deep/.u-dropdown__menu__item {
      justify-content: center;
    }
  }

  &-dashboard {
    height: 220rpx;
    flex: 0 0 110rpx;

    .dashboard {
      width: 690rpx;
      height: 220rpx;
      background: #ffffff;
      box-shadow: 0rpx -20rpx 82rpx 16rpx rgba(112, 112, 112, 0.21);
      border-radius: 40rpx;
      margin: -110rpx auto 0;
      position: relative;
      z-index: 1;
      display: flex;
      padding-top: 69rpx;

      &::after {
        content: " ";
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        height: 89rpx;
        width: 1px;
        background-color: #b8b8b8;
      }

      &-item {
        width: 50%;

        .amount {
          font-size: 54rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #4e95fc;
          line-height: 54rpx;
        }

        .desc {
          margin-top: 23rpx;
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #6e6e6e;
          line-height: 36rpx;
        }

        &:first-child {
          padding-left: 61rpx;
        }

        &:last-child {
          padding-left: 59rpx;
        }
      }
    }
  }

  &-tabs {
    flex: 1;

    /deep/.u-tabs-item {
      // mar
    }

    padding: 30rpx 12rpx;
  }
}
</style>
